importJar("org.slf4j:slf4j-api:jar:1.7.21");
importJar("org.slf4j:slf4j-simple:jar:1.7.21");
importJar('com.sproutsocial:nsq-j:jar:0.9.4');

importClass("com.sproutsocial.nsq.Subscriber");
importClass("com.sproutsocial.nsq.Publisher");
importClass("com.sproutsocial.nsq.MessageHandler");

function Nsq() {
    // 创建一个消息消费者. lookupHosts 地址， callback 回调处理器.
    this.sub = function (lookupHosts, topic, channel, callback) {
        // 创建消息者.
        var innerSubscriber = new Subscriber(lookupHosts);
        // 订阅转发消息.
        var messsageHandler =  new MessageHandler(function (msg) {
            var result = callback(msg);
            // 只有返回false 才会拦截. 其它情况都会触发，消息完成.
            if (false !== result) {
                msg.finish();
            }
        });
        // 开始处理.
        innerSubscriber.subscribe(topic, channel, messsageHandler);
        return {
            close:function () {
                innerSubscriber.stop();
            }
        };
    };
    // 创建一个消息发送器.
    this.pub = function (lookupHosts) {
        var publisher = {};
        // 内部类.
        var innerPublisher =  new Publisher(lookupHosts);
        // 转发发送消息.
        publisher.send = function(topic, msg) {
            innerPublisher.publish(topic, util.getBytes(msg))
        };
        publisher.close = function () {
            innerPublisher.stop();
        };
        return publisher;
    }
}